// 1. React核心库
import React, { useRef, useState } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Space, Tag, Popconfirm, Badge, message } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, TeamOutlined, ReloadOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { RoleExtension } from '@/services/generated';

const RolesPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);

  // 删除操作
  const handleDelete = async (record: RoleExtension) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.permissions.permissionsRolesDestroy({ id: record.id! });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = async (selectedRowKeys: React.Key[]) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await Promise.all(
        selectedRowKeys.map(id => apiClients.permissions.permissionsRolesDestroy({ id: Number(id) }))
      );
      message.success(`成功删除${selectedRowKeys.length}条记录`);
      actionRef.current?.reload();
    } catch (error) {
      message.error('批量删除失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<RoleExtension>[] = [
    { title: 'ID', dataIndex: 'id', width: 80, sorter: true },
    {
      title: '角色名称',
      dataIndex: ['group', 'name'],
      ellipsis: true,
      copyable: true,
      render: (text, record) => (
        <Space>
          <span>{text}</span>
          {record.is_system && <Tag color="orange">系统角色</Tag>}
        </Space>
      ),
    },
    {
      title: '角色代码',
      dataIndex: 'code',
      width: 150,
      render: (text) => <Tag color="geekblue">{text}</Tag>,
    },
    {
      title: '角色级别',
      dataIndex: 'level',
      width: 100,
      search: false,
      render: (text) => (
        <Badge
          count={Number(text) || 0}
          color={Number(text) <= 2 ? 'red' : Number(text) <= 5 ? 'orange' : 'blue'}
          showZero
        />
      ),
      sorter: true,
    },
    {
      title: '权限数量',
      dataIndex: 'permissions_count',
      width: 100,
      search: false,
      render: (text) => <Badge count={Number(text) || 0} color="green" showZero />,
    },
    {
      title: '用户数量',
      dataIndex: 'users_count',
      width: 100,
      search: false,
      render: (text) => <Badge count={Number(text) || 0} color="blue" showZero />,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_,record) => (
        <Tag color={record.status === 'active' ? 'green' : 'red'}>
          {record.status === 'active' ? '激活' : '禁用'}
        </Tag>
      ),
      valueType: 'select',
      valueEnum: {
        active: { text: '激活', status: 'Success' },
        inactive: { text: '禁用', status: 'Error' },
      },
    },
    { title: '描述', dataIndex: 'description', ellipsis: true, search: false },
    { title: '创建时间', dataIndex: 'created_at', valueType: 'dateTime', sorter: true, search: false },
    {
      title: '操作',
      width: 300,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small" wrap>
          <Button type="link" size="small" href={`/permissions/roles/detail/${record.id}`} icon={<EditOutlined />}>
            详情
          </Button>
          <Button type="link" size="small" href={`/permissions/role-permissions/${record.id}`} icon={<KeyOutlined />}>
            权限
          </Button>
          <Button type="link" size="small" href={`/permissions/role-users/${record.id}`} icon={<TeamOutlined />}>
            用户
          </Button>
          <Button type="link" size="small" href={`/permissions/roles/edit/${record.id}`}>
            编辑
          </Button>
          {!record.is_system && (
            <Popconfirm title="确定删除？" onConfirm={() => handleDelete(record)}>
              <Button type="link" size="small" danger loading={loading} icon={<DeleteOutlined />}>
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<RoleExtension>
           scroll={{x: 'max-content'}}
        headerTitle="角色管理"
        actionRef={actionRef}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        pagination={{ pageSize: 20, showSizeChanger: true, showQuickJumper: true }}
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys) => {
            console.log('选中的行:', selectedRowKeys);
          },
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>已选择 {selectedRowKeys.length} 项</span>
            <Button type="link" size="small" onClick={onCleanSelected}>取消选择</Button>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => (
          <Space size={16}>
            <Popconfirm title={`确定删除选中的${selectedRowKeys.length}条记录？`} onConfirm={() => handleBatchDelete(selectedRowKeys)}>
              <Button type="link" size="small" danger>批量删除</Button>
            </Popconfirm>
          </Space>
        )}
        toolBarRender={() => [
          <Button key="create" type="primary" icon={<PlusOutlined />} href="/permissions/roles/create">新建角色</Button>,
          <Button key="refresh" icon={<ReloadOutlined />} onClick={() => actionRef.current?.reload()}>刷新</Button>,
        ]}
        request={async (params, sort) => {
          try {
            await autoLoginInDev();
            const response = await apiClients.permissions.permissionsRolesList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.group?.name || params.code,
              status: params.status,
              isSystem: params.is_system,
              ordering: sort && Object.keys(sort).length > 0 ?
                Object.entries(sort).map(([key, value]) => value === 'ascend' ? key : `-${key}`).join(',') :
                undefined,
            });
            return {
              data: response?.data?.items || [],
              success: true,
              total: response?.data?.total || 0
            };
          } catch (error) {
            message.error('获取数据失败');
            return { data: [], success: false, total: 0 };
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default RolesPage;
